package com.vb.ecm.web.custom.importcontent;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfLoginInfo;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.web.common.AcsService;
import com.documentum.web.common.ArgumentList;
import com.documentum.web.common.ClientNetworkLocationService;
import com.documentum.web.common.WrapperRuntimeException;
import com.documentum.web.formext.action.ActionService;
import com.documentum.web.formext.component.Component;
import com.documentum.web.formext.config.ConfigService;
import com.documentum.web.formext.config.Context;
import com.documentum.web.formext.config.IConfigElement;
import com.documentum.web.formext.config.IConfigLookup;
import com.documentum.web.formext.session.AuthenticationService;
import com.documentum.web.formext.session.DocbaseUtils;
import com.documentum.web.formext.session.IAuthenticationService;
import com.documentum.web.formext.session.PasswordExpiredException;
import com.documentum.web.formext.session.SessionManagerHttpBinding;

public class RedirectComponent extends Component {
	/**
	 * 
	 */
	private static final Logger LOGGER = Logger.getLogger(RedirectComponent.class);
	private static final long serialVersionUID = 1L;
	// private String strRequestedDocbase="ECM_REPO_DEV";
	// String
	// url="http://HQ-ECMAPP-DEV.hq.icbv.com:8080/webtop/action/import_los?objectId=0c01e24080000107";
	private ArgumentList transId;
	// private String m_strObjectId = "090285208000a809";
	private String m_strObjectId;
	private boolean bSuccessfullyAuthenticated;
	private boolean m_bIsDistributedDeployment;
	String bocsID = "BOCS Server";
	private boolean m_bUsingAnonymousAccount;
	private boolean m_bLogoffAnonymousAccounts;
	private Context actionContext;
	private String objectId;

	public RedirectComponent() {
		m_bUsingAnonymousAccount = false;
		m_bLogoffAnonymousAccounts = true;

	}

	@Override
	public void onInit(ArgumentList args) {
		super.onInit(args);
		LOGGER.debug("Enter into onInit() of RedirectComponent: Import Soft Copy Documents Started");
		try {
			// code here

			/*
			 * You have to add your component to:
			 * \WEB-INF\classes\com\documentum\web\formext\Environmen
			 * t.properties ->non_docbase_component.[last +1]=[your comp]
			 */
			m_strObjectId = args.get("objectId");
			LOGGER.debug("Transaction ID received from URL:" + m_strObjectId);
			String strRequestedDocbase = DocbaseUtils.getDocbaseNameFromId(m_strObjectId);
			LOGGER.debug("Requested Docbase to Import Documents:" + strRequestedDocbase);
			if (strRequestedDocbase == null) {
				LOGGER.error("ECM DOCBROKER DOWN");
				showError("ECM DOCBROKER DOWN");
				setComponentPage("error");
				return;
			}
			LOGGER.debug("strRequestedDocbase:" + strRequestedDocbase);
			SessionManagerHttpBinding.setClientDocbase(strRequestedDocbase);
			LOGGER.debug("Checking whether user already authanticated o not");
			if (!isAuthenticated(strRequestedDocbase)) {
				LOGGER.debug("is Not Authenticated");
				attemptAnonymousLogin(strRequestedDocbase);
				// setComponentJump("drlauthenticate", args, getContext());
			} else {
				LOGGER.debug("is Authenticated");
				// attemptAnonymousLogin(strRequestedDocbase);

				m_bUsingAnonymousAccount = Boolean.TRUE.equals(getPageContext().getRequest().getAttribute("redirectUsingAnonymousAccount"));
				m_bLogoffAnonymousAccounts = Boolean.TRUE.equals(lookupBoolean("defaultaccounts.logoffoncomplete"));
				LOGGER.debug("m_bUsingAnonymousAccount:" + m_bUsingAnonymousAccount);
				// LOGGER.debug("m_bLogoffAnonymousAccounts:" +
				// m_bLogoffAnonymousAccounts);
			}

			initNetworkLocationControls();

			HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
			String fullUrl = request.getRequestURL().toString();
			// StringBuffer sb=new StringBuffer();
			LOGGER.debug("request URL:" + fullUrl);

			// String strRequestedDocbase =
			// DocbaseUtils.getDocbaseNameFromId(m_strObjectId);

			for (String s1 : fullUrl.split("=")) {

				if (s1.startsWith("http")) {
					LOGGER.debug("s1:" + s1);
				}
				if (s1.startsWith("09")) {
					LOGGER.debug("trans id:" + s1);
					if (s1.contains("&")) {

						String s2[] = s1.split("&");
						LOGGER.debug("trans_id:" + s2[0]);
						args.add("trans_id", s2[0]);
						// m_strObjectId=s2[0];

					} else {
						LOGGER.debug("trans_id in else:" + s1);
						args.add("trans_id", s1);
						// m_strObjectId=s1;

					}
				}
			}

			LOGGER.debug("transaction id in args:" + args.get("trans_id"));

			try {
				IDfSysObject tempCabinet = (IDfSysObject) getDfSession().getObjectByQualification("dm_cabinet where object_name='Temp' ");
				objectId = tempCabinet.getString("r_object_id");
			} catch (DfException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			args.replace("objectId", objectId);// dev

			String objectId = args.get("objectId");
			LOGGER.debug("objId:" + objectId);
			// sb.append(request.getContextPath()).append("/action/import_los?objectId/").append(args.get("objectId"));
			actionContext = new Context(getContext());
			actionContext.set("objectId", args.get("objectId"));
			actionContext.set("trans_id", args.get("trans_id"));

			args.add(CustomImportContentContainer.T_ID, args.get("trans_id"));

			ActionService.execute("import_los", args, actionContext, this, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LOGGER.error(e);
			e.printStackTrace();
			setComponentPage("error");
		}

		// setComponentJump("import_los", args, getContext());

		LOGGER.debug("Exit from onInit() of RedirectComponent");
		// super.onInit(args);
	}

	protected void initNetworkLocationControls() throws Exception {
		m_bIsDistributedDeployment = false;
		if (AcsService.getInstance().isAcsReadTransferEnabled() || AcsService.getInstance().isAcsWriteTransferEnabled()) {
			List networkLocations = ClientNetworkLocationService.getInstance().getAvailableClientNetworkLocations();
			if (networkLocations == null || networkLocations.isEmpty()) {
				m_bIsDistributedDeployment = false;
			} else {
				LOGGER.debug("BOCS ID:" + bocsID);

				if (bocsID == null || bocsID.isEmpty()) {
					m_bIsDistributedDeployment = false;
					AcsService.getInstance().getAcsReadTransferPreferences().allowBocsTransfer(false);
					LOGGER.debug("BOCS ID Empty***, So that Documents retrived from default BOCS" + bocsID);
					// IDfNetworkLocationEntry dfNetworkLocation =
					// (IDfNetworkLocationEntry) networkLocations.get(0);
					// ClientNetworkLocationService.getInstance().setClientNetworkLocationId(("HQ-ECMBRV-UAT"));
					LOGGER.debug("m_bIsDistributedDeployment:-" + m_bIsDistributedDeployment);
					LOGGER.debug("Connected BOCS:" + ClientNetworkLocationService.getInstance().getClientNetworkLocationId());
				} else {
					m_bIsDistributedDeployment = true;
					AcsService.getInstance().getAcsReadTransferPreferences().allowBocsTransfer(true);
					LOGGER.debug("BOCS ID NOT Empty, So that Documents retrived from " + bocsID);
					// IDfNetworkLocationEntry dfNetworkLocation =
					// (IDfNetworkLocationEntry) networkLocations.get(0);
					ClientNetworkLocationService.getInstance().setClientNetworkLocationId((bocsID));
					LOGGER.debug("m_bIsDistributedDeployment:-" + m_bIsDistributedDeployment);
					LOGGER.debug("Connected BOCS:" + ClientNetworkLocationService.getInstance().getClientNetworkLocationId());
				}
			}
		}
	}

	public boolean isAuthenticated(String strDocbase) throws Exception {
		boolean bAuthenticated = false;
		LOGGER.debug("SessionManagerHttpBinding.isConnectedToDocbase(strDocbase)===" + SessionManagerHttpBinding.isConnectedToDocbase(strDocbase));
		if (SessionManagerHttpBinding.isConnectedToDocbase(strDocbase)) {
			bAuthenticated = true;
		} else {
			try {
				// LOGGER.debug("AuthenticationService=="+AuthenticationService.getService());
				IAuthenticationService authService = AuthenticationService.getService();

				HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
				HttpServletResponse response = (HttpServletResponse) getPageContext().getResponse();
				String authDocbase = authService.authenticate(request, response, strDocbase);
				LOGGER.debug("authDocbase:" + authDocbase);
				if (authDocbase != null) {
					bAuthenticated = authDocbase.equals(strDocbase);
				}
			} catch (Exception ignore) {
				ignore.printStackTrace();
			}

		}
		LOGGER.debug("isAuthenticated:" + bAuthenticated);
		return bAuthenticated;
	}

	private void attemptAnonymousLogin(String strRequestedDocbase) throws Exception {
		boolean bAttemptAnonymousAuthentication = false;
		if (m_strObjectId != null && m_strObjectId.startsWith("09")) {
			bAttemptAnonymousAuthentication = true;
		}
		if (bAttemptAnonymousAuthentication) {
			LOGGER.debug("bAttemptAnonymousAuthentication:" + bAttemptAnonymousAuthentication);
			boolean success = authenticateUsingAnonymousAccount(strRequestedDocbase);
			if (success) {
				LOGGER.debug("authenticateUsingAnonymousAccount:" + success);
				getPageContext().getRequest().setAttribute("drlUsingAnonymousAccount", Boolean.TRUE);
			}
		}
	}

	private boolean authenticateUsingAnonymousAccount(String strRequestedDocbase) throws Exception {
		boolean bSuccessfullyAuthenticated = true;
		IDfLoginInfo loginInfo = getAnonymousAccountLoginInfo(strRequestedDocbase);

		Context ctx = getContext();
		if (strRequestedDocbase != null) {
			ctx = new Context(getContext());
			ctx.set("docbase", strRequestedDocbase);
		}

		// loginInfo.setUser("ecmdmadmin");
		// loginInfo.setPassword("Abc@123456");
		if (loginInfo != null) {
			try {

				AuthenticationService.getService().login(getPageContext().getSession(), strRequestedDocbase, loginInfo.getUser(), loginInfo.getPassword(), loginInfo.getDomain());
				bSuccessfullyAuthenticated = true;
				LOGGER.debug("bSuccessfullyAuthenticated:" + bSuccessfullyAuthenticated);
			} catch (PasswordExpiredException ignore) {
				bSuccessfullyAuthenticated = false;
			} catch (DfException ignore) {
				bSuccessfullyAuthenticated = false;
			}
		}
		return bSuccessfullyAuthenticated;
	}

	private IDfLoginInfo getAnonymousAccountLoginInfo(String strRequestedDocbase) throws Exception {
		IDfLoginInfo loginInfo = null;
		IConfigLookup configLookup = ConfigService.getConfigLookup();
		Context ctx = getContext();
		LOGGER.debug("getAnonymousAccountLoginInfo:" + strRequestedDocbase);
		if (strRequestedDocbase != null) {
			ctx = new Context(getContext());
			ctx.set("docbase", strRequestedDocbase);
		}
		IConfigElement accInfo = configLookup.lookupElement((new StringBuilder()).append("component[id=").append(getComponentId()).append("].defaultaccounts.account").toString(),
				ctx);
		if (accInfo == null) {
			accInfo = configLookup.lookupElement((new StringBuilder()).append("component[id=").append(getComponentId()).append("].defaultaccounts.defaultaccount").toString(), ctx);
			LOGGER.debug("accInfo:" + accInfo);
			loginInfo = new DfLoginInfo();
			loginInfo.setUser("ecmdmadmin");
			loginInfo.setPassword("Abc@123456");

		}

		if (accInfo != null) {
			String strUserId = accInfo.getChildElement("username").getValue();
			LOGGER.debug("strUserId:" + strUserId);
			if (strUserId != null) {
				loginInfo = new DfLoginInfo();
				loginInfo.setUser(strUserId);
				IConfigElement newpwElem = accInfo.getChildElement("new-pw");
				LOGGER.debug("new-pw:" + newpwElem.getValue());
				if (newpwElem != null) {
					try {
						// loginInfo.setPassword(TrustedAuthenticatorUtils.decryptByDES(newpwElem.getValue()));
						loginInfo.setPassword((newpwElem.getValue()));
					} catch (Exception e) {
						throw new WrapperRuntimeException(e);
					}
				}

				String strDomain = accInfo.getChildElement("domain").getValue();
				if (strDomain != null && strDomain.length() > 0) {
					loginInfo.setDomain(strDomain);
				}
			}
		}
		return loginInfo;
	}

	private void showError(String strErrorNlsId) throws Exception {
		boolean m_showPermissionsErrorMessage = true;
		boolean m_hideControls = true;
		String m_strPermissionsErrorMessageNlsId = strErrorNlsId;
	}

}
